package sg.edu.nus.iss.team4.entity.dao.factory;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import sg.edu.nus.iss.team4.entity.dao.IAnswerDAO;
import sg.edu.nus.iss.team4.entity.dao.IQuestionDAO;
import sg.edu.nus.iss.team4.entity.dao.impl.AnswerDAOImpl;
import sg.edu.nus.iss.team4.entity.dao.impl.QuestionDAOImpl;

public class DAOFactory implements IDAOFactory {

	private static DAOFactory daoFactory;
	private static SessionFactory sessionFactory;
	
	private DAOFactory() { }
	
	public static DAOFactory getDAOFactory() {
		if(daoFactory == null) {
			daoFactory = new DAOFactory();
			sessionFactory = buildSessionFactory();
		}
		return daoFactory;
	}

	public IQuestionDAO getQuestionDAO() {
		return new QuestionDAOImpl(sessionFactory);
	}
	
	public IAnswerDAO getAnswerDAO() {
		return new AnswerDAOImpl(sessionFactory);
	}

	private static SessionFactory buildSessionFactory() {
		try {
			return new Configuration().configure("/sg/edu/nus/iss/team4/entity/mapping/hibernate.cfg.xml").buildSessionFactory();
		} catch(Throwable throwable) {
			System.err.println("Initial SessionFactory creation failed." + throwable);
			throw new ExceptionInInitializerError(throwable);
		}
	}

}
